import React, { useState, useEffect } from 'react';
import { View, Text } from '@tarojs/components';
import { Tabs } from '@nutui/nutui-react-taro';
import { Toast } from '@nutui/nutui-react-taro';
import {
  Warning,
  Bell,
  Message,
  Del
} from '@nutui/icons-react-taro';
import './index.scss';
import { notificationApi } from '../../services/notificationApi';

const NotificationPage = () => {
  const [activeTab, setActiveTab] = useState('0');
  const [notificationList, setNotificationList] = useState([]);
  const [touchStartX, setTouchStartX] = useState(0);
  const [touchStartY, setTouchStartY] = useState(0);
  const [currentSwipedItem, setCurrentSwipedItem] = useState(null);
  const [swipeDistance, setSwipeDistance] = useState({});
  const [showToast, setShowToast] = useState(false);
  const [toastMsg, setToastMsg] = useState('');
  const [hasShownSwipeHint, setHasShownSwipeHint] = useState(false);

  const getNotification = async () => {
    const res = await notificationApi.getNotificationList();
    setNotificationList(res);
  }

  useEffect(() => {
    getNotification();
  }, []);

  // 获取通知图标和背景色
  const getNotificationIcon = (category) => {
    switch (category) {
      case 'forewarning':
        return {
          icon: <Warning />,
          iconColor: '#FF6961',
          bgColor: '#FFF1F0'
        };
      case 'system':
        return {
          icon: <Bell />,
          iconColor: '#5C9DFF',
          bgColor: '#F0F5FF'
        };
      default:
        return {
          icon: <Message />,
          iconColor: '#9A7CFF',
          bgColor: '#F5F0FF'
        };
    }
  };

  const tabs = [
    { title: '全部', value: '0' },
    { title: '预警', value: '1' },
    { title: '系统', value: '2' }
  ];

  const handleTabChange = (value) => {
    setActiveTab(value);
    // 切换标签时重置滑动状态
    setCurrentSwipedItem(null);
    setSwipeDistance({});
  };

  // 根据当前标签筛选通知
  const getFilteredNotifications = () => {
    if (activeTab === '0') return notificationList;
    if (activeTab === '1') return notificationList.filter(item => item.category === 'forewarning');
    if (activeTab === '2') return notificationList.filter(item => item.category === 'system');
    return notificationList;
  };

  // 已读
  const handleReadNotificationApi = async (id) => {
    try {
      const res = await notificationApi.readNotification(id);
      await getNotification();
      console.log(res);
    } catch (error) {
      showTaroToast('已读失败');
    }
  };

  // 删除
  const handleDeleteNotificationApi = async (id) => {
    try {
      const res = await notificationApi.deleteNotification(id);
      await getNotification();
      console.log(res);
    } catch (error) {
      showTaroToast('删除失败');
    }
  };

  // 格式化时间显示
  const formatTime = (timeString) => {
    if (!timeString) return '';
    const date = new Date(timeString);
    const now = new Date();
    const diffDays = Math.floor((now - date) / (24 * 60 * 60 * 1000));

    if (diffDays === 0) {
      return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (diffDays === 1) {
      return '昨天';
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  };

  // 显示提示
  const showTaroToast = (message) => {
    setToastMsg(message);
    setShowToast(true);
    setTimeout(() => {
      setShowToast(false);
    }, 2000);
  };

  // 标记通知为已读
  const handleReadNotification = (id) => {
    // 找到当前通知
    const notification = notificationList.find(item => item.notification_id === id);
    if (!notification) return;

    handleReadNotificationApi(id);

    // 如果通知未读，标记为已读并提示右滑删除
    if (!notification.is_read && !hasShownSwipeHint) {
      // 在实际应用中，这里会调用API来更新通知状态
      console.log('标记通知已读:', id);

      // 显示右滑删除提示
      showTaroToast('右滑可删除此通知');

      // 记录已经显示过提示
      setHasShownSwipeHint(true);

      // 阻止事件冒泡，避免触发其他点击事件
      return false;
    }

    // 如果已读，可以执行其他操作，如查看详情等
    console.log('查看通知详情:', id);
  };

  // 处理滑动开始
  const handleTouchStart = (e, id) => {
    setTouchStartX(e.touches[0].clientX);
    setTouchStartY(e.touches[0].clientY);
  };

  // 处理滑动中
  const handleTouchMove = (e, id) => {
    if (currentSwipedItem && currentSwipedItem !== id) {
      return; // 如果有其他项目正在滑动，不处理当前滑动
    }

    const touchEndX = e.touches[0].clientX;
    const touchEndY = e.touches[0].clientY;

    // 计算水平和垂直滑动距离
    const deltaX = touchStartX - touchEndX;
    const deltaY = touchStartY - touchEndY;

    // 如果垂直滑动大于水平滑动，应该是上下滚动，不是左右滑动
    if (Math.abs(deltaY) > Math.abs(deltaX)) {
      return;
    }

    // 左滑操作（露出删除按钮）
    if (deltaX > 30) { // 滑动距离超过30像素才触发
      setCurrentSwipedItem(id);
      const moveX = Math.min(deltaX, 80); // 最大滑动距离为80px

      // 更新滑动距离状态
      setSwipeDistance(prev => ({
        ...prev,
        [id]: moveX
      }));

      // 获取当前滑动的DOM元素并应用变换
      const element = document.getElementById(`notification-item-${id}`);
      if (element) {
        element.style.transform = `translateX(-${moveX}px)`;
      }
    }
    // 右滑操作（恢复原状）
    else if (deltaX < -30 && currentSwipedItem === id) {
      setSwipeDistance(prev => ({
        ...prev,
        [id]: 0
      }));

      const element = document.getElementById(`notification-item-${id}`);
      if (element) {
        element.style.transform = 'translateX(0)';
        setCurrentSwipedItem(null);
      }
    }
  };

  // 处理滑动结束
  const handleTouchEnd = (e, id) => {
    if (currentSwipedItem !== id) return;

    // 获取当前滑动距离
    const distance = swipeDistance[id] || 0;

    // 如果滑动距离超过40px，完全展开删除按钮
    if (distance > 40) {
      setSwipeDistance(prev => ({
        ...prev,
        [id]: 80
      }));

      const element = document.getElementById(`notification-item-${id}`);
      if (element) {
        element.style.transform = 'translateX(-80px)';
      }
    } else {
      // 否则恢复原状
      setSwipeDistance(prev => ({
        ...prev,
        [id]: 0
      }));

      const element = document.getElementById(`notification-item-${id}`);
      if (element) {
        element.style.transform = 'translateX(0)';
        setCurrentSwipedItem(null);
      }
    }
  };

  // 删除通知
  const handleDeleteNotification = async (id) => {
    try {
      await handleDeleteNotificationApi(id);
      // 重置滑动状态，确保删除后UI状态正确
      setCurrentSwipedItem(null);
      setSwipeDistance(prev => ({
        ...prev,
        [id]: 0
      }));
      // 显示删除成功提示
      showTaroToast('删除成功');
    } catch (error) {
      showTaroToast('删除失败');
    }
  };

  return (
    <View className="notification-page">
      <Tabs
        value={activeTab}
        onChange={handleTabChange}
        activeType="button"
      >
        {tabs.map((tab) => (
          <Tabs.TabPane key={tab.value} title={tab.title} value={tab.value} />
        ))}
      </Tabs>

      <View className="notification-list">
        {getFilteredNotifications().length === 0 ? 
        <View className="empty-notification">
          <View className="empty-icon">
            <Bell color="#CCCCCC" size="48" />
          </View>
          <Text className="empty-text">暂无通知</Text>
        </View> :
          getFilteredNotifications().map(notification => {
            const { icon, iconColor, bgColor } = getNotificationIcon(notification.category);
            return (
              <View
                className="notification-item-wrapper"
                key={notification.notification_id}
              >
                <View
                  id={`notification-item-${notification.notification_id}`}
                  className="notification-item"
                  onTouchStart={(e) => handleTouchStart(e, notification.notification_id)}
                  onTouchMove={(e) => handleTouchMove(e, notification.notification_id)}
                  onTouchEnd={(e) => handleTouchEnd(e, notification.notification_id)}
                  onClick={() => handleReadNotification(notification.notification_id)}
                >
                  <View className="icon-container" style={{ backgroundColor: bgColor }}>
                    <View className="notification-icon" style={{ color: iconColor }}>
                      {icon}
                    </View>

                    {/* 只有未读的通知才显示小红点 */}
                    {!notification.is_read && (
                      <View className="notification-dot" style={{ backgroundColor: '#FF6961' }}></View>
                    )}
                  </View>

                  <View className="notification-content">
                    <View className="notification-header">
                      <Text className="notification-title">{notification.title}</Text>
                      <Text className="notification-time">{formatTime(notification.created_at)}</Text>
                    </View>
                    <Text className="notification-message">{notification.content}</Text>
                  </View>
                </View>

                {/* 删除按钮 */}
                <View
                  className="delete-button"
                  onClick={() => handleDeleteNotification(notification.notification_id)}
                >
                  <Del />
                </View>
              </View>
            );
          })
        }

      </View>

      {/* Toast提示 */}
      {showToast && <Toast visible={showToast} content={toastMsg} />}
    </View>
  );
};

export default NotificationPage;